import React, { createContext, useContext, useState } from 'react';

interface AuthContextType {
  isLoggedIn: boolean;
  userName: string;
  login: (name?: string) => void;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType>({
  isLoggedIn: false,
  userName: '',
  login: () => {},
  logout: () => {},
});

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userName, setUserName] = useState('赵四');

  const login = (name?: string) => {
    console.log('login called');
    setIsLoggedIn(true);
    if (name) setUserName(name);
  };

  const logout = () => {
    console.log('logout called');
    setIsLoggedIn(false);
    setUserName('');
  };

  console.log('AuthProvider render', isLoggedIn, userName);

  return (
    <AuthContext.Provider value={{ isLoggedIn, userName, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext); 